package com.hezy.base.data;

import android.util.Log;

import com.hezy.base.constant.BaseConstant;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpManager {

    private static String TAG = "HttpManager";

    private static final long HTTP_CONNECT_TIMEOUT = 30L;
    private static final long HTTP_READ_TIMEOUT = 10L;
    private static volatile HttpManager mInstance;

    private HttpManager() {
    }

    public static HttpManager getInstance() {
        if (mInstance == null) {
            synchronized (HttpManager.class) {
                if (mInstance == null) {
                    mInstance = new HttpManager();
                }
            }
        }
        return mInstance;
    }

    public <T> T getService(String baseUrl, Class<T> service) {
        return create(baseUrl).create(service);
    }

    private Retrofit create(String baseUrl) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(HTTP_READ_TIMEOUT, TimeUnit.SECONDS);

        if (BaseConstant.HTTP_LOG_ENABLE) {
            builder.addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.w(TAG, "OkHttp: " + message);
                }
            }).setLevel(HttpLoggingInterceptor.Level.BODY));
        }

        OkHttpClient client = builder.build();
        return create(baseUrl, client, GsonConverterFactory.create(), RxJavaCallAdapterFactory.create());
    }

    private Retrofit create(String baseUrl, OkHttpClient client, Converter.Factory gsonFactory, CallAdapter.Factory callFactory) {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)
                .addConverterFactory(gsonFactory)
                .addCallAdapterFactory(callFactory)
                .build();
    }
}
